package com.cc.service

import com.cc.common.exception.ServerException
import com.cc.common.model.Query
import com.cc.mapper.RepositoryMapper
import com.cc.model.Repository
import com.cc.model.convert.RepositoryConvert
import com.cc.model.dto.RepositoryDto
import com.cc.model.dto.ext.TreeDTO
import com.mybatisflex.core.paginate.Page
import com.mybatisflex.core.query.QueryWrapper
import com.mybatisflex.kotlin.extensions.db.paginate
import com.mybatisflex.kotlin.extensions.db.queryOne
import com.mybatisflex.kotlin.extensions.kproperty.eq
import com.mybatisflex.spring.service.impl.ServiceImpl
import org.springframework.stereotype.Service

/**
 * RepositoryService
 * @author aa
 * @since 2024/4/24
 * @version 1.0
 */
@Service
class RepositoryService(private val repositoryConvert: RepositoryConvert) : ServiceImpl<RepositoryMapper, Repository>() {

    fun add(repository: RepositoryDto) = save(repositoryConvert.toEntity(repository))

    fun update(repository: RepositoryDto) = update(repositoryConvert.toEntity(repository), QueryWrapper())

    fun findRepListByPage(query: Query<RepositoryDto?>): Page<RepositoryDto> {
        return paginate(Page.of<Repository>(query.page, query.limit)) {
            query.p?.let { a ->
                where {
                    Repository::repName eq a.repName
                }.orderBy(Repository::addTime, false)
            }
        }.map {
            repositoryConvert.toDto(it)
        }

    }

    fun getRepositoryDetail(id: String) = id.run {
        getById(this)?.let { repositoryConvert.toDto(it) } ?: throw ServerException("数据不存在")
    }

    fun findRepList() = list().map {
        repositoryConvert.toDto(it)
    }


    fun findRepTreeById(id: String, type: String?): TreeDTO<String>? {
        getById(id)?.let {
            null
        } ?: throw ServerException("数据不存在")

    }

    fun repNameExist(repId: String, repName: String): Boolean {
        if (repName.isBlank() || repId.isBlank()) return true
        return queryOne<Repository> {
            where {
                Repository::repName eq repName
            }
        }?.let {
            it.id == repId
        } ?: false
    }
}